var params = "";
var Image0 = "";//图片地址
var Image1 = "";
var name = "";
var phone = "";
var codes = "";
var houseId = "";
var faultTypeId = "";//故障类型的ID
var faultInfoTypeId = "";//故障类型详情的ID
var faultNames = "";
var peopleString ="";
var publicName ="";//公共报修类型的名称
var createId = "";//当前用户的ID
var openId = "";
$(function(e){
	receiveData();
	dataInit();
	updateImg();
});

function dataInit(){
	eventInit();
	codes = $.req("code");
	AjaxPostUtil.request({url : path+"1853f065ae4845f2a235af6449c18767", params:{codes:codes}, type : 'json', callback : function(json){
		console.log(json);
		if(json.returnCode == "-999"){//重新登记
			openId = json.bean.openId;
			location.href='../../html/wechat_signup/wechat_signup.html?openId='+openId;
		}else if(json.returnCode == "-888"){
			//关闭当前页面，返回到微信主页面
			swal({ title : "提示", text : "信息正在审核中...", type : "warning" ,closeOnConfirm:false, closeOnCancel:false },function(){
					wx.closeWindow();
			});
		}else if(json.returnCode == "-777"){
			swal({ title : "提示", text : "信息审核失败，请重新登记！", type : "warning",closeOnConfirm:false, closeOnCancel:false },function(){
				openId = json.bean.openId;
				location.href='../../html/wechat_signup/wechat_signup.html?openId='+openId;
			});
			
		}else if(json.returnCode == 0){
			$("#hInfo1").val(json.bean.hInfo);
			$("#hInfo").val(json.bean.hInfo);
			$("#name").val(json.bean.familyName);
			$("#phone").val(json.bean.familyPhone);
			houseId = json.bean.houseId;
			createId = json.bean.id;
			getFaultByType();
		}else{
			swal({ title : "警告", text : "请重新打开页面", type : "warning" ,closeOnConfirm:false, closeOnCancel:false },function(){
				wx.closeWindow();
			});
		}
	}});
	
}

function eventInit(){
	
	//日期插件
	if($(".iDate.date").length>0){
		$(".iDate.date").datetimepicker({
			locale:"zh-cn",
	        format:"YYYY-MM-DD",
	        dayViewHeaderFormat:"YYYY年 MMMM"
	    });
	}
	//选择公共报修类型
	$('body').on('click','#publicInfoName',function(){
		$("#selectPublicInfoName").modal("show");
	});
	//公共报修类型保存
	$('body').on('click', '#publicInfoNameBtn', function(e){
		var publicString = $("#PublicInfoName").val();
		var a = publicString.indexOf("-");
		publicName = publicString.substr(a+1);//公共故障类型的名称
		faultTypeId = parseInt(publicString.substr(0,a));//公共故障类型的ID
		$("#publicInfoName").val(publicName);
		$("#selectPublicInfoName").modal("hide");
	});
	
	//选择个人报修类型
	$('body').on('click', '#FaultName', function(e){
		$("#selectFaultName").modal("show");
	});
	//个人报修类型保存
	$('body').on('click', '#faultNameBtn', function(e){
		peopleString = $("#faultName").val();
		var a = peopleString.indexOf("-");
		var peopleName = peopleString.substr(a+1);//故障类型的名称
		faultTypeId = parseInt(peopleString.substr(0,a));//故障类型的ID
		$("#FaultName").val(peopleName);
		$("#selectFaultName").modal("hide");
		
	});
	
	//选择个人报修类型详情信息
	$('body').on('click', '#InfoName', function(e){
		faultNames = $("#FaultName").val();
		if(faultNames == null || faultNames == "" || faultNames == "故障类别"){
			swal({ title : "警告", text : '请选择故障类别！', type : "warning" });
		}else if(faultNames != null || faultNames != "" || faultNames != "故障类别"){
			
			var params ={
					faultId : faultTypeId
			}
			AjaxPostUtil.request({url : path+"ebe8a52195f14a5facd2583ae238f150", params : params, type : 'json', callback : function(json){
				if(json.returnCode == 0){
					console.log(json);
					var source = $("#selectinfoName").html();
					var template = Handlebars.compile(source);
					$("#infoName").html(template(json));
					$("#selectInfoName").modal("show");
				}else{
					swal({ title : "错误", text : json.returnMessage, type : "error" }); 
				}
			}});
		}
		
		
	});
	//个人报修类型详情保存
	$('body').on('click','#infotNameBtn',function(e){
		var peopleInfo = $("#infoName").val();
		var a = peopleInfo.indexOf("-");
		var peopleNames = peopleInfo.substr(a+1);//故障类型的名称
		faultInfoTypeId = parseInt(peopleInfo.substr(0,a));//故障类型详情的ID
		$("#InfoName").val(peopleNames);
		$("#selectInfoName").modal("hide");
	});
	
	//公共报修单提交
	$('body').on('click', '#publicBtn', function(e){
		
		if(isNull($("#publicInfoName").val())){
			swal({ title : "警告", text : "请选择公共报修类型!", type : "warning" }); 
			return;
		}else if(isNull($("#repairText1").val())){
			swal({ title : "警告", text : "请填写故障内容!", type : "warning" }); 
			return;
		}else{
			params={
					repairText : $("#repairText1").val(),
					faultInfoId : 0,//初始值0
					repairTitle : publicName,
					type : 2,
					roomNum : houseId,
					faultId : faultTypeId,
					repairDate : 0,
					repairDateDoor : 0,
					repairImg : Image1
			}
		}
		AjaxPostUtil.request({url : path+"284e28b3c9b648a3bae0defbae4980d7", params : params, type : 'json', callback : function(json){
			
			if(json.returnCode == 0){
				swal({ title : "成功", text : "报修成功！", type : "success" ,closeOnConfirm:false, closeOnCancel:false }, function(){
					wx.closeWindow();
				}); 
			}else{
				swal({ title : "错误", text : json.returnMessage, type : "error" }); 
			}
			
		}});
	});	
	
	//个人故障报修单提交
	$('body').on('click', '#repairBtn', function(e){
		if(isNull($("#selsctTime").val()) || ($("#selectTime").val()=='请选择具体时间')){
			swal({ title : "错误", text : "请选择维修时间!", type : "error" }); 
			return;
		}else if(isNull($("#FaultName").val())){
			swal({ title : "错误", text : "请选择故障类别!", type : "error" }); 
			return;
		}else if(isNull($("#InfoName").val())){
			swal({ title : "错误", text : "请选择故障详情!", type : "error" }); 
			return;
		}else if(isNull($("#repairText").val())){
			swal({ title : "错误", text : "请填写故障内容!", type : "error" }); 
			return;
		}else{ 
			params = {
					faultInfoId : faultInfoTypeId,
					faultId : faultTypeId,
					repairDate : $("#text1").val(),
					repairDateDoor : $("#selsctTime").val(),
					repairText : $("#repairText").val(),
					repairTitle : $("#FaultName").val() +" "+$("#InfoName").val(),
					type : 1,
					repairImg : Image0,
					roomNum : houseId
			}
		}

		AjaxPostUtil.request({url : path+"284e28b3c9b648a3bae0defbae4980d7", params : params, type : 'json', callback : function(json){
			
			if(json.returnCode == 0){
				swal({ title : "成功", text : "报修成功！", type : "success" ,closeOnConfirm:false, closeOnCancel:false },function(){
					wx.closeWindow();
				});
				
			}else{
				swal({ title : "错误", text : json.returnMessage, type : "error" }); 
			}
			
		}});
	});
	
	//跳转报修记录
	$('body').on('click', '#search2', function(e){
		location.href = "../../html/wechat_repair/repairRecord.html?creatId="+createId;
	});
	//个人报修故障内容字数限制
	$("#repairText").keyup(function(){  
         var text = $(this).val();  
         //中文字数统计  
         str = (text.replace(/\w/g,"")).length;  
         //非汉字的个数  
         abcnum = text.length-str;  
         total = str+abcnum;  
         if(total > 500){  
             swal({ title : "警告", text : "您输入的字数超限！", type : "warning" }); 
         }  
         $("#words").html(total);  
	});
	//公共报修故障内容字数限制
	$("#repairText1").keyup(function(){  
        var text = $(this).val();  
        //中文字数统计  
        str = (text.replace(/\w/g,"")).length;  
        //非汉字的个数  
        abcnum = text.length-str;  
        total = str+abcnum;  
        if(total > 500){  
        	 swal({ title : "警告", text : "您输入的字数超限！", type : "warning" }); 
        }  
        $("#pwords").html(total);  
	});
}

function getFaultByType(){
	
	//故障类型的查询
	AjaxPostUtil.request({url : path+"6c82fba8f9f84010a68e32839e5190b0", params : {}, type : 'json', callback : function(jsonMation){
		if(jsonMation.returnCode == 0){
			console.log(jsonMation);
			//个人报修
			Handlebars.registerHelper("compare1", function(v1, v2, options){
				if(v1 == 1){
					return options.fn(this);
				}else{
					return options.inverse(this);
				}
			});
			
			var source = $("#selectfaultName").html();
			var template = Handlebars.compile(source);
			$("#faultName").html(template(jsonMation));
			//公共报修
			Handlebars.registerHelper("compare2", function(v1, v2, options){
				if(v1==2){
					return options.fn(this);
				}else{
					return options.inverse(this);
				}
			});
			var source = $("#selectpublicFaultName").html();
			var template = Handlebars.compile(source);
			$("#PublicInfoName").html(template(jsonMation));
			
		}else{
			swal({ title : "错误", text : jsonMation.returnMessage, type : "error" }); 
		}
	}});
	
}
function updateImg() {
	
	//个人报修图片上传
	$("#ImageZero").uploadPreview({
		Img : "ImgZero"
	});
	$("#ImageZero").fileupload(
	{
		url : path + "dd25d8a6660749acb7a7ab8880843815",
		disableImageResize : /Android(?!.*Chrome)|Opera/ .test(window.navigator.userAgent),
		autoUpload : true,// 是否自动上传
		maxFileSize : 999000,
		imageMaxWidth : 1000,
		imageMaxHeight : 800,
		imageQuality : 0.6,
		dataType : 'json',
		acceptFileTypes : /(\.|\/)(jpe?g|png|svg)$/i
	}).on('fileuploadadd', function(e, data) {
		var uploadFile = data.files[0];
		fileName = uploadFile.name;
		var reg = ".(jpg|png|jpeg|svg)$";
		var re = new RegExp(reg);
		
		if (fileName.length > 50) {
			swal({ title : "错误", text : "文件名长度不能大于50", type : "error" }); 
			$.staticPic('ImgZero', 'logoDiv');
			return false;
		} else if (!re.test(fileName.toLowerCase())) {
			swal({ title : "错误", text : "文件必须为jpg/jpeg/png格式", type : "error" });
			$.staticPic('ImgZero', 'logoDiv');
			return false;
		} else if (uploadFile.size > 6000000) { // 2mb
			swal({ title : "错误", text : "文件不能大于2M", type : "error" });
			$.staticPic('ImgZero', 'logoDiv');
			return false;
		}
	}).on('fileuploaddone', function(e, data) {
		if (isNull(data.result.bean)) {
			$.staticPic('ImgZero', 'logoDiv');
			swal({ title : "错误", text : data.result.returnMessage, type : "error" });
		} else {
			 Image0  = data.result.bean.optionPath;
			 swal({ title : "成功", text : "上传成功", type : "success" });
		}
	}).on('fileuploadfail', function(e, data) {
		$.staticPic('ImgZero', 'logoDiv');
		swal({ title : "错误", text : "上传失败，图片格式不正确", type : "error" });
	});
	
	
	//公共报修图片上传
	$("#publicImageOne").uploadPreview({
		Img : "public_ImageOne"
	});
	$("#publicImageOne").fileupload(
			{
				url : path + "bc7ec409e6c14f40824b0f643d47edfc",
				disableImageResize : /Android(?!.*Chrome)|Opera/ .test(window.navigator.userAgent),
				autoUpload : true,// 是否自动上传
				maxFileSize : 999000,
				imageMaxWidth : 1000,
				imageMaxHeight : 800,
				imageQuality : 0.6,
				dataType : 'json',
				acceptFileTypes : /(\.|\/)(jpe?g|png|svg)$/i
			}).on('fileuploadadd', function(e, data) {
				var uploadFile = data.files[0];
				fileName = uploadFile.name;
				var reg = ".(jpg|png|jpeg|svg)$";
				var re = new RegExp(reg);
				
				if (fileName.length > 50) {
					swal({ title : "错误", text : "文件名长度不能大于50", type : "error" }); 
					$.staticPic('public_ImageOne', 'logoDiv');
					return false;
				} else if (!re.test(fileName.toLowerCase())) {
					swal({ title : "错误", text : "文件必须为jpg/jpeg/png格式", type : "error" });
					$.staticPic('public_ImageOne', 'logoDiv');
					return false;
				} else if (uploadFile.size > 6000000) { // 2mb
					swal({ title : "错误", text : "文件不能大于2M", type : "error" });
					$.staticPic('public_ImageOne', 'logoDiv');
					return false;
				}
			}).on('fileuploaddone', function(e, data) {
				if (isNull(data.result.bean)) {
					$.staticPic('public_ImageOne', 'logoDiv');
					swal({ title : "错误", text : data.result.returnMessage, type : "error" });
				} else {
					 Image1  = data.result.bean.optionPath;
					 swal({ title : "成功", text : "上传成功", type : "success" });
				}
			}).on('fileuploadfail', function(e, data) {
				$.staticPic('public_ImageOne', 'logoDiv');
				swal({ title : "错误", text : "上传失败，图片格式不正确", type : "error" });
			});

}

